﻿using System;
namespace CSUtils {
    public class CTime {
        const string _tag = "CTime.系统时间";
        #if UNITY_EDITOR
        public static int frameCount {get;private set;}
        public static float time {get;private set;}
        public static float timeScale {get;private set;}
        public static float deltaTime {get;private set;}
        public static float deltaTime2 {get;private set;}
        public static float realtimeSinceStartup {get;private set;}
        public static string currTimeStr {get;private set;} = "0.000_0";
        #else
        public static int frameCount;
        public static float time;
        public static float timeScale;
        public static float deltaTime;
        public static float deltaTime2;
        public static float realtimeSinceStartup;
        public static string currTimeStr;
        #endif
        /// <summary>
        /// 获取时间戳
        /// </summary> 
        public static double GetTotalMilliseconds() {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            timeMillis = ts.TotalMilliseconds;
            return timeMillis;
        }

        public static double timeMillis;

        public static void SetData(int frameCount, float time, float timeScale, float deltaTime, float realtimeSinceStartup, string currTimeStr) {
            CTime.frameCount = frameCount;
            CTime.time = time;
            CTime.timeScale = timeScale;
            CTime.deltaTime = deltaTime;
            deltaTime2 = realtimeSinceStartup - CTime.realtimeSinceStartup;
            CTime.realtimeSinceStartup = realtimeSinceStartup;
            CTime.currTimeStr = currTimeStr;
        }

        static CBgUpdate _bgUpdate;

        static double _startTime;

        public static void Init_BgTime() {
            if(_bgUpdate != null) {
                _bgUpdate.End();
            }
            _startTime = DateTime.Now.ToLocalTime().ToFileTimeUtc();
            _startTime *= 0.0000001f;
            _bgUpdate = CBgUpdate.Start("CTime.BG", delegate {
                frameCount++;
                double currTime0 = DateTime.Now.ToLocalTime().ToFileTimeUtc();
                currTime0 *= 0.0000001f;
                var last_realtimeSinceStartup = realtimeSinceStartup;
                realtimeSinceStartup = (float)(currTime0 - _startTime);
                time = realtimeSinceStartup;
                deltaTime = realtimeSinceStartup - last_realtimeSinceStartup;
                deltaTime2 = deltaTime;
                currTimeStr = realtimeSinceStartup + "_" + frameCount;
                //CLog.i(_tag, $"currTime={realtimeSinceStartup}.....{deltaTime}");
            }, 15);
        }
    }
}
